﻿using DevExpress.XtraEditors;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace ConfExpert.Forms.ImportWizards
{
    public partial class Hackett_Tip1 : XImportWizard
    {
        public Hackett_Tip1()
        {
            InitializeComponent();

            Init("Hackett Sezon Sipariş Dosyası", false);
            btnSave.ItemClick += BtnSave_ItemClick;

            this.FileDone += Hackett_Tip1_FileDone;
            this.ProcessStart += Hackett_Tip1_ProcessStart;
            this.ProcessDone += Hackett_Tip1_ProcessDone;
        }

        DataTable dtResult;

        void Hackett_Tip1_ProcessStart()
        {
            dtResult = new DataTable();
            dtResult.TableName = "Order";
            dtResult.Columns.Add("ProductId", typeof(int));


            DataSet dsResult = new DataSet();
            dsResult.Tables.Add(dtResult);

            dtResult.ColumnChanged -= dtResult_ColumnChanged;
            //gvSource.FocusedColumnChanged += gvSource_FocusedColumnChanged;
        }

        void Hackett_Tip1_ProcessDone()
        {
            var distinctValues = dtResult.AsEnumerable()
                      .Select(row => new
                      {
                          Kod = row.Field<string>("Article"),
                      })
                      .Distinct().ToList();

            string codes = string.Join(",", Array.ConvertAll(distinctValues.ToArray(), i => i.Kod));


            DataTable dtId = Session.DataManager.ExecuteDataTable("GetProductIdByCode", codes.Replace("-", "/"));
            foreach (DataRow drParsed in dtResult.Rows)
            {
                DataRow[] drIds = dtId.Select("Kod='" + drParsed["Article"].ToString().Replace("-", "/") + "'");
                if (drIds.Length == 1)
                    drParsed["ProductId"] = (int)drIds[0]["ProductId"];
            }


            MasterGrid.Init(dtResult);



            //MasterGrid.SutunEkle("TotalQty", typeof(decimal), "SUM(Child({FK}).Qty)");

            MasterGrid.AddSummary();
            MasterGrid.AddSummary("TotalQty");
            MasterGrid.MakeReadOnly("ProductId");
            MasterGrid.BestFitColumns();
            dtResult.ColumnChanged += dtResult_ColumnChanged;

            btnSave.Enabled = true;
        }

        void dtResult_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            if (e.Column == dtResult.Columns["ProductId"])
            {
                dtResult.ColumnChanged -= dtResult_ColumnChanged;
                int productId = (int)e.Row["ProductId"];
                string artikel = (string)e.Row["Article"];
                foreach (DataRow dr in dtResult.Rows)
                {
                    if ((string)dr["Article"] == artikel)
                    {
                        dr["ProductId"] = productId;
                    }
                }
                dtResult.ColumnChanged += dtResult_ColumnChanged;
            }
        }

        private void BtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DataRow[] drs = dtResult.Select("ProductId is null");
            if (drs.Length > 0)
            {
                DialogResult dr = XtraMessageBox.Show("Product'ı set edilmemiş satırlar var. Bu ekranda, düzeltmeleri yapmak çok daha kolay. Düzeltmek ister misiniz?", "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (dr == System.Windows.Forms.DialogResult.No)
                    Kaydet();
            }
            else
                Kaydet();
        }

        private void Kaydet()
        {
            if (dtResult.Select("DagilimId is null").Length > 0)
            {
                ShowErrorMessage("Dağılımı belli olmayan satırlar var. Dağılım sütunu boş olan satırlar için Excel dosyasını kontrol edin.");
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            string xml = dtResult.SerializeChanges();    //bak!
            ExecuteNonQuery("InsHackettOrder", xml);
            this.Cursor = Cursors.Default;
            ShowInfoMessage("Siparişler başarıyla aktarıldı.");

            this.Cursor = Cursors.Default;

        }

        //void gvSource_FocusedColumnChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs e)
        //{
        //    //gvSource.FocusedColumn.Caption = "<b>" + gvSource.FocusedColumn.Caption + "</b>";
        //    if (e.PrevFocusedColumn != null)
        //        e.PrevFocusedColumn.AppearanceHeader.Font = new Font(gvSource.FocusedColumn.AppearanceHeader.Font, FontStyle.Regular);

        //    if (e.FocusedColumn != null)
        //        e.FocusedColumn.AppearanceHeader.Font = new Font(gvSource.FocusedColumn.AppearanceHeader.Font, FontStyle.Bold);
        //}

        void Hackett_Tip1_FileDone(DataSet ds, string FileName)
        {
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                DataTable dt = ds.Tables[i];
                DataTable dtSheet = ProcessSheet(dt);

                dtSheet.Columns.Add("SheetName", typeof(string));
                dtSheet.Columns.Add("DosyaAdi", typeof(string));

                foreach (DataRow dr in dtSheet.Rows)
                {
                    dr["SheetName"] = dt.TableName;
                    dr["DosyaAdi"] = FileName;  //*
                }

                dtResult.Merge(dtSheet);
            }
        }

        private static DataTable ProcessSheet(DataTable dt)
        {
            DataTable dtDagilimV = Session.DataManager.ExecuteDataTableByQuery("select * from dagilimVertical where DagilimId in (10,19,23,33) ");
            List<int> availableDagilimIds = new List<int>();
            DataTable dtNew = new DataTable();

            int startIndex = -1;
            int endIndex = -1;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][0].ToString().ToUpper() == "START")
                {
                    startIndex = i + 1;
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (dt.Rows[i][j].ToString().ToUpper() == "END")
                        {
                            endIndex = j;
                        }

                    }
                    break;
                }
            }

            Dictionary<int, string> columnsInt = new Dictionary<int, string>();
            Dictionary<string, int> columnsStr = new Dictionary<string, int>();

            for (int j = 0; j < endIndex; j++)
            {
                string caption = dt.Rows[startIndex][j].ToStr().Replace(" ", "");
                string dagilimId = dt.Rows[startIndex - 1][j].ToStr();


                if (caption != string.Empty)
                {
                    if (dagilimId != "" && dagilimId != "start")
                    {
                        string filter = "DagilimId=" + dagilimId + " and Beden='" + caption + "'";
                        caption = dtDagilimV.Select(filter)[0]["Name"].ToString();


                        columnsInt.Add(j, caption);
                    }
                    else
                    {
                        columnsInt.Add(j, caption);
                        columnsStr.Add(caption, j);
                    }
                    dtNew.Columns.Add(caption, typeof(string));
                }
            }

            for (int i = startIndex + 1; i < dt.Rows.Count; i++)
            {
                string control = "";
                for (int c = 0; c < 5; c++)
                    control += dt.Rows[i][c].ToStr();

                if (control == "")
                    continue;

                DataRow drNew = dtNew.NewRow();
                foreach (int j in columnsInt.Keys)
                {
                    DataRow dr = dt.Rows[i];

                    string fieldName = columnsInt[j];

                    string val = dr[j].ToString();
                    if (fieldName.StartsWith("A") && fieldName.Length == 3)
                    {
                        int rowDagilimId = dt.Rows[i][columnsStr["DagilimId"]].ToInt(-1);
                        int colDagilimId = dt.Rows[startIndex - 1][j].ToInt(-1);
                        if (rowDagilimId != colDagilimId)
                            continue;
                        else
                        {
                            string beden = dt.Rows[startIndex][j].ToStr();
                            string filter = "DagilimId=" + rowDagilimId + " and Beden='" + beden + "'";
                            fieldName = dtDagilimV.Select(filter)[0]["Name"].ToString();
                        }
                        drNew[fieldName] = val.ToInt();
                    }
                    else
                    {
                        drNew[fieldName] = val.ToString();
                    }

                }
                dtNew.Rows.Add(drNew);
            }



            return dtNew;


        }
        /*
        public static object GetCount(object DBCarpan,int carpan)
        {

            //decimal sumRollQty = (decimal)dtParsed.Compute("sum(qty)", "");
            //if (!total.Equals(sumRollQty))
            //    ShowErrorMessage("Dosyadaki toplam metre ile topların metrelerinin toplamı farklı. Kontrol edin !!!");

            foreach (DataColumn dc in dtNew.Columns)
            {
                dc.ColumnName = dc.Caption == "" ? dc.ColumnName : dc.Caption;
            }


            DataTable dtData = new DataTable();

            DataTable dtDagilim = new DataTable();
            dtDagilim.Columns.Add("Model", typeof(string));
            dtDagilim.Columns.Add("x37", typeof(int));
            dtDagilim.Columns.Add("x38", typeof(int));
            dtDagilim.Columns.Add("x39", typeof(int));
            dtDagilim.Columns.Add("x40", typeof(int));
            dtDagilim.Columns.Add("x41", typeof(int));
            dtDagilim.Columns.Add("x42", typeof(int));
            dtDagilim.Columns.Add("x43", typeof(int));
            dtDagilim.Columns.Add("x44", typeof(int));
            dtDagilim.Columns.Add("x45", typeof(int));
            dtDagilim.Columns.Add("x46", typeof(int));
            dtDagilim.Columns.Add("x47", typeof(int));
            dtDagilim.Columns.Add("x48", typeof(int));
            dtDagilim.Columns.Add("S", typeof(int));
            dtDagilim.Columns.Add("M", typeof(int));
            dtDagilim.Columns.Add("L", typeof(int));
            dtDagilim.Columns.Add("XL", typeof(int));
            dtDagilim.Columns.Add("XXL", typeof(int));
            dtDagilim.Columns.Add("XXXL", typeof(int));
            dtDagilim.Columns.Add("Total", typeof(int), "isnull(x37,0)+isnull(x38,0)+isnull(x39,0)+isnull(x40,0)+isnull(x41,0)+isnull(x42,0)+isnull(x43,0)+isnull(x44,0)+isnull(x45,0)+isnull(x46,0)+isnull(x47,0)+isnull(x48,0)+isnull(S,0)+isnull(M,0)+isnull(L,0)+isnull(XL,0)+isnull(XXL,0)+isnull(XXXL,0)");


            try
            {
                bool isFirstColumnEmpty = true;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    string firstCell = dr[0].ToStr();
                    if (firstCell != "")
                    {
                        isFirstColumnEmpty = false;
                        break;
                    }
                }
                if (isFirstColumnEmpty)
                    dt.Columns.RemoveAt(0);

                List<string> labels = new List<string>();

                int firstCellIndex = -1;
                int DagilimStart = -1;
                int DagilimEnd = -1;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    string firstCell = dr[0].ToString();
                    if (firstCell.ToUpper() == "RATIO")
                    {
                        DagilimStart = i + 1;

                    }
                    else if (firstCell.ToUpper() == "RATIO END")
                    {
                        DagilimEnd = i;

                    }
                }

                if (DagilimStart == -1 || DagilimEnd == -1)
                {
                    throw new ApplicationException("RATIO/RATIO END satırları bulunamadı!");
                }


                for (int i = 0; i < DagilimStart; i++)
                {
                    DataRow dr = dt.Rows[i];
                    string firstCell = dr[0].ToString();

                    if (firstCell == "RÉFÉRENCES" || firstCell == "REFERENCES")
                    {
                        firstCellIndex = i + 2;
                        for (int j = 2; j < dt.Columns.Count; j++)
                        {
                            string label = dr[j].ToString();
                            if (label != "")
                            {
                                labels.Add(label);
                            }
                            else
                            {
                                break;
                            }
                        }
                        break;
                    }
                }

                int ratioLastColIndex = 0;
                for (int cIndex = 0; cIndex < dt.Columns.Count; cIndex++)
                {
                    if (dt.Rows[DagilimStart - 1][cIndex].ToStr() == "")
                    {
                        ratioLastColIndex = cIndex - 1;
                        break;
                    }

                }

                if (DagilimStart != -1 && DagilimEnd != -1)
                {
                    DataRow captions = dt.Rows[DagilimStart - 1];

                    for (int i = DagilimStart; i < DagilimEnd; i++)
                    {
                        DataRow dr = dt.Rows[i];


                        DataRow drDagilim = dtDagilim.NewRow();
                        drDagilim[0] = dr[0].ToStr().Replace(" ", "").ToUpper();

                        for (int j = 1; j < ratioLastColIndex; j++)
                        {
                            string fieldName = captions[j].ToStr();
                            if (Char.IsNumber(fieldName, 0))
                                fieldName = "x" + fieldName;

                            drDagilim[fieldName] = dr[j];
                        }
                        dtDagilim.Rows.Add(drDagilim);
                    }
                }


                dtData.Columns.Add("Article", typeof(string));
                dtData.Columns.Add("Model", typeof(string));
                dtData.Columns.Add("TotalQty", typeof(int));

                dtData.Columns.Add("x37", typeof(int));
                dtData.Columns.Add("x38", typeof(int));
                dtData.Columns.Add("x39", typeof(int));
                dtData.Columns.Add("x40", typeof(int));
                dtData.Columns.Add("x41", typeof(int));
                dtData.Columns.Add("x42", typeof(int));
                dtData.Columns.Add("x43", typeof(int));
                dtData.Columns.Add("x44", typeof(int));
                dtData.Columns.Add("x45", typeof(int));
                dtData.Columns.Add("x46", typeof(int));
                dtData.Columns.Add("x47", typeof(int));
                dtData.Columns.Add("x48", typeof(int));
                dtData.Columns.Add("S", typeof(int));
                dtData.Columns.Add("M", typeof(int));
                dtData.Columns.Add("L", typeof(int));
                dtData.Columns.Add("XL", typeof(int));
                dtData.Columns.Add("XXL", typeof(int));
                dtData.Columns.Add("XXXL", typeof(int));

                string caption = "";
                bool skip = false;
                for (int i = firstCellIndex; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    string firstCell = dr[0].ToString();

                    List<string> rowValues = new List<string>();
                    for (int j = 0; j < labels.Count + 2; j++)
                    {
                        string val = dr[j].ToString();
                        rowValues.Add(val);
                    }

                    bool allEmpty = true;
                    foreach (string v in rowValues)
                    {
                        if (v != "")
                        {
                            allEmpty = false;
                            break;
                        }
                    }
                    if (allEmpty)
                    {
                        continue;
                    }
                    else
                    {

                        if (rowValues[0] != "")
                        {
                            caption = rowValues[0].Trim();
                            if (caption.ToLower() == "total" || caption.ToLower() == "grand total")
                            {
                                skip = true;
                                continue;
                            }
                            else if (caption == "RÉFÉRENCES" || caption == "REFERENCES")
                            {
                                skip = false;
                                continue;
                            }
                        }
                        if (!skip)
                        {
                            if (rowValues[1] != "")
                            {
                                rowValues[0] = caption + "/" + rowValues[1].PadLeft(2, '0');
                                rowValues[1] = "";
                            }

                            for (int k = 2; k < rowValues.Count; k++)
                            {
                                DataRow drNew = dtData.NewRow();
                                drNew[0] = rowValues[0];
                                string model = labels[k - 2].Replace(" ", "").ToUpper();
                                drNew["Model"] = model;
                                int baseQty = rowValues[k].ToInt(-1);
                                if (baseQty == -1) baseQty = 0;
                                drNew["TotalQty"] = baseQty;


                                DataRow[] drsDagilim = dtDagilim.Select("Model='" + model + "'");
                                if (drsDagilim.Length == 1)
                                {
                                    DataRow drCarpan = drsDagilim[0];
                                    int total = drCarpan["Total"].ToInt(-1);
                                    if (total > 0)
                                    {
                                        int carpan = baseQty / total;

                                        drNew["x37"] = GetCount(drCarpan["x37"], carpan);
                                        drNew["x38"] = GetCount(drCarpan["x38"], carpan);
                                        drNew["x39"] = GetCount(drCarpan["x39"], carpan);
                                        drNew["x40"] = GetCount(drCarpan["x40"], carpan);
                                        drNew["x41"] = GetCount(drCarpan["x41"], carpan);
                                        drNew["x42"] = GetCount(drCarpan["x42"], carpan);
                                        drNew["x43"] = GetCount(drCarpan["x43"], carpan);
                                        drNew["x44"] = GetCount(drCarpan["x44"], carpan);
                                        drNew["x45"] = GetCount(drCarpan["x45"], carpan);
                                        drNew["x46"] = GetCount(drCarpan["x46"], carpan);
                                        drNew["x47"] = GetCount(drCarpan["x47"], carpan);
                                        drNew["x48"] = GetCount(drCarpan["x48"], carpan);
                                        drNew["S"] = GetCount(drCarpan["S"], carpan);
                                        drNew["M"] = GetCount(drCarpan["M"], carpan);
                                        drNew["L"] = GetCount(drCarpan["L"], carpan);
                                        drNew["XL"] = GetCount(drCarpan["XL"], carpan);
                                        drNew["XXL"] = GetCount(drCarpan["XXL"], carpan);
                                        drNew["XXXL"] = GetCount(drCarpan["XXXL"], carpan);
                                    }
                                }

                                dtData.Rows.Add(drNew);

                            }

                        }
                    }
                }
                return dtData;
            }
            catch (ApplicationException aex)
            {
                MessageBox.Show(aex.Message);
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;

            }


            if (DBCarpan == DBNull.Value)
                return DBNull.Value;
            else if (DBCarpan.ToInt() == 0)
                return DBNull.Value;
            else if (DBCarpan.ToInt() * carpan == 0)
                return DBNull.Value;
            else
                return DBCarpan.ToInt() * carpan;
        }
                    */
    }
}